package com.org.lg.base;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jpay.ext.kit.HttpKit;
import com.jpay.ext.kit.PaymentKit;
import com.org.lg.bean.PayConfig;
import com.org.lg.constant.Constant;

/**
 * @author LG
 * @version 1.0.0
 * @date 2018-10-31 10:26
 */
@RestController
public abstract class WxNotifyController {
	
	/**
	 * 微信支付的异步回调
	 * @param request
	 * @return
	 */
	@RequestMapping(Constant.NOTIFY_WX_NOTIFY_URL)
	public abstract String notifyUrl(HttpServletRequest request);
	
	/**
	 * 校验微信异步通知
	 * @param request
	 * @return
	 */
	protected boolean verifyNotify(HttpServletRequest request) {
		String xmlMsg = HttpKit.readData(request);
		System.out.println("支付通知="+xmlMsg);
		Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
		String result_code  = params.get(Constant.RESULT_CODE);
		if(PaymentKit.verifyNotify(params, PayConfig.WxPay.partnerKey)){
			return "SUCCESS".equals(result_code);
		}else {
			return false;
		}
	};
	
	/**获取微信支付通知的参数
	 * @param request
	 * @param key
	 * @return
	 */
	protected String getValueByKey(HttpServletRequest request,String key) {
		String xmlMsg = HttpKit.readData(request);
		Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
		return params.get(key);
	}
	
	/**
	 * 告诉微信服务器别老特么给我请求，我已经在支付后成功处理自己的业务逻辑了，but微信服务器不是太靠谱最好在自己业务逻辑加一个标识
	 * @return
	 */
	protected String OK() {
		Map<String, String> xml = new HashMap<String, String>();
		xml.put("return_code", "SUCCESS");
		xml.put("return_msg", "OK");
		return PaymentKit.toXml(xml);
	}
}
